package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.InvoiceStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.po.AdminInvoice;
import com.ygqh.baby.po.AdminInvoiceDetail;
import com.ygqh.baby.po.AdminSku;
import com.ygqh.baby.po.AdminSupplierInvoice;
import com.ygqh.baby.service.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhangSai on 2016/11/4 0004.
 */

@Controller
@RequestMapping("/admin/invoice")
public class InvoiceController extends  BaseController<Object, java.lang.Long>{
    @Autowired
    private AdminSupplierInvoiceService adminSupplierInvoiceService;
    @Autowired
	private FileService fileService;
    @Autowired
    private AdminInvoiceService adminInvoiceService;
    @Autowired
    private AdminInvoiceDetailService adminInvoiceDetailService;
    @Autowired
    private AdminSkuService adminSkuService;

	@RequestMapping("searchSupplierInvoice")
	@ResponseBody
	public Map<String,Object> searchSupplierInvoice(String q,QueryInfo queryInfo,String salesCompany) {

		ResultSet<AdminSupplierInvoice> resultSet=adminSupplierInvoiceService.search(queryInfo, q,salesCompany);

		return resultSet.toDatatables(null);
	}
	@RequestMapping("searchInvoice")
	@ResponseBody
	public Map<String,Object> searchInvoice(String q,String applyPerson,Date startDate,QueryInfo queryInfo,Date endDate, String invoiceTitle) {
		ResultSet<AdminInvoice> resultSet=adminInvoiceService.search(queryInfo, q, applyPerson, startDate, endDate, invoiceTitle);
		return resultSet.toDatatables(null);
	}
	//更新供应商发票的归还状态
	@RequestMapping("updateSupplierInvoice")
	@ResponseBody
	public Message updateSupplierInvoice(Long id) {
		AdminSupplierInvoice adminSupplierInvoice=new AdminSupplierInvoice();
		adminSupplierInvoice.setId(id);
		adminSupplierInvoice.setUpdateBy(getSession().getTrueName());
		adminSupplierInvoice.setUpdateTime(new Date());
		adminSupplierInvoice.setInvoiceStatus(true);
		adminSupplierInvoiceService.update(adminSupplierInvoice);

	    return SUCCESS_MESSAGE;

	}
	//导入供应商发票
	@RequestMapping("readTemplate")
	@ResponseBody
	public List<Map<String,Object>> readTemplate(@RequestParam("uploadFile") MultipartFile uploadFile,HttpServletRequest request, HttpServletResponse response) throws IOException{
		InputStream is = uploadFile.getInputStream();
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");


		 List<Map<String,Object>> invoiceList = new ArrayList<Map<String,Object>>();
		 List<String> invoiceNoList = new ArrayList<>();


		try {
			// Read the Sheet
			for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
				XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
				if (xssfSheet == null) {
					continue;
				}
				// Read the Row
				for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
					XSSFRow xssfRow = xssfSheet.getRow(rowNum);
					if (xssfRow == null) {
						continue;
					}
					if (xssfRow != null) {
						Map<String,Object> map=new HashMap<String, Object>();

						String invoiceNo = xssfRow.getCell(0).toString();
						String invoiceDate = format.format(xssfRow.getCell(1).getDateCellValue());

						String invoiceMoney = xssfRow.getCell(2).toString();
						String taxMoney = xssfRow.getCell(3).toString();
						String taxRate = xssfRow.getCell(4).toString();
						String salesCompany = xssfRow.getCell(5).toString();
						String salesNo = xssfRow.getCell(6).toString();
						String checkResult = xssfRow.getCell(7).toString();
						String checkDate = format.format(xssfRow.getCell(8).getDateCellValue());
						map.put("invoiceCode", "");
						map.put("invoiceNo", invoiceNo);
						map.put("invoiceDate", invoiceDate);
						map.put("invoiceMoney", invoiceMoney);
						map.put("taxMoney", taxMoney);
						map.put("taxRate", taxRate);
						map.put("salesCompany", salesCompany);
						map.put("salesNo", salesNo);
						map.put("checkResult", checkResult);
						map.put("checkDate", checkDate);
						map.put("createBy", getSession().getTrueName());
						map.put("createTime", format.format(new Date()));
						String r="";

						if(map.get("invoiceNo")==null)
							r+="发票号码不能为空";
						if(r!=""){
							continue;
						}
						if(map.get("invoiceCode")==null)
							  r+="发票代码不能为空";
						if(map.get("invoiceDate")==null)
							r+="开票不能为空";
						if(map.get("invoiceMoney")==null)
							r+="开票金额不能为空";

						if(invoiceNoList.contains(map.get("invoiceNo"))){
							r+="数据重复";
						}else{
							invoiceNoList.add(map.get("invoiceNo").toString());
						}
						map.put("remark", r);
						invoiceList.add(map);

					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return invoiceList;
	}
	@SuppressWarnings("static-access")
	private String getValue(XSSFCell hssfCell) {
		if (hssfCell == null)
			return null;

		if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
			// 返回布尔类型的值
			return String.valueOf(hssfCell.getBooleanCellValue());
		} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
			DecimalFormat df1 = new DecimalFormat("0");
			Double d=hssfCell.getNumericCellValue();
			return df1.format(d);
		} else {
			// 返回字符串类型的值
			return hssfCell.getStringCellValue();
		}
	}

	private String getDoubleValue(XSSFCell hssCell){
		DecimalFormat df2 = new DecimalFormat("0.00");
		Double d=hssCell.getNumericCellValue();
		return df2.format(d);

	}



	@RequestMapping("saveBatchSupplierInvoice")
	@ResponseBody
	public Message saveBatchSupplierInvoice(String supplierInvoice,HttpServletRequest request,HttpServletResponse response) {
		List<AdminSupplierInvoice> adminInvoice=JSON.parseObject(supplierInvoice, new TypeReference<List<AdminSupplierInvoice>>(){});
		adminSupplierInvoiceService.saveBatchSupplierInvoice(adminInvoice);
		return SUCCESS_MESSAGE;
	}
	@RequestMapping("saveInvoice")
	@ResponseBody
	public Message saveInvoice(String invoice,HttpServletRequest request,HttpServletResponse response) {
		AdminInvoice adminInvoice=JSON.parseObject(invoice, AdminInvoice.class);
		if(adminInvoice.getId()==null){
			adminInvoice.setCreateBy(getSession().getTrueName());
			adminInvoice.setCreateTime(new Date());
		}else{
			adminInvoice.setUpdateBy(getSession().getTrueName());
			adminInvoice.setUpdateTime(new Date());
		}
		adminInvoiceService.saveOrUpdate(adminInvoice);
		return SUCCESS_MESSAGE;

	}
	@RequestMapping("getInvoice")
	@ResponseBody
	public AdminInvoice getInvoice(Long id,HttpServletRequest request,HttpServletResponse response) {
		return adminInvoiceService.findById(id);

	}
	//更新发票的状态
	@RequestMapping("updateInvoiceStatus")
	@ResponseBody
	public Message updateInvoiceStatus(Long id,String cancelReason) {
			AdminInvoice adminInvoice=new AdminInvoice();
			adminInvoice.setId(id);
			adminInvoice.setUpdateBy(getSession().getTrueName());
			adminInvoice.setUpdateTime(new Date());
			adminInvoice.setInvoiceStatus(InvoiceStatus.Cancel);
			adminInvoice.setCancelReason(cancelReason);
			adminInvoiceService.update(adminInvoice);

		    return SUCCESS_MESSAGE;

		}
	//更新发票的状态
		@RequestMapping("isExistsInvoice")
		@ResponseBody
		public Boolean isExistsInvoice(Long id,String invoiceNo) {
			 return adminInvoiceService.isExistsInvoice(id,invoiceNo);
		}

		//导入供应商发票
		@RequestMapping("readDetailTemplate")
		@ResponseBody
		public List<Map<String,Object>> readDetailTemplate(@RequestParam("uploadFile") MultipartFile uploadFile,HttpServletRequest request, HttpServletResponse response) throws IOException{
			InputStream is = uploadFile.getInputStream();
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);

			List<Map<String,Object>> invoiceList=new ArrayList<Map<String,Object>>();
			Map<String,Object> skulist=new HashMap<String, Object>();
			BigDecimal totalMoney=new BigDecimal("0");


			try {
				// Read the Sheet
				for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
					XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
					if (xssfSheet == null) {
						continue;
					}
					// Read the Row
					for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
						XSSFRow xssfRow = xssfSheet.getRow(rowNum);
						if (xssfRow == null) {
							continue;
						}
						if (xssfRow != null) {
							Map<String,Object> map=new HashMap<String, Object>();
							String skuCode = getValue(xssfRow.getCell(0));

							String itemPrice = getDoubleValue(xssfRow.getCell(2));
							String itemAmount = getValue(xssfRow.getCell(3));
							String itemUnit = xssfRow.getCell(4).toString();
							String r="";
							if(skuCode==null)
								r+="SkuCode不能为空";
							if(itemPrice==null)
							   r+="单价不能为空";
							if(itemAmount==null)
								   r+="数量不能为空";

							if(r!=""){
								map.put("remark", r);
								continue;
							}
							//根据SKUCode 获取sku名称
							AdminSku adminSku=adminSkuService.findBySkuCode(skuCode);
							if(adminSku!=null){
								//判断sku是否已经存在list 中
								if(skulist.containsKey(adminSku.getProductName())){
									//循环list 将当前的数量单价进行合计
									for(Map<String,Object> m:invoiceList){
										if(m.get("itemName").equals(adminSku.getProductName())){
											BigDecimal price=new BigDecimal(m.get("itemPrice").toString());
											Long amount=Long.valueOf(m.get("itemAmount").toString());
											BigDecimal total=price.multiply(new BigDecimal(amount));
											total=total.add(new BigDecimal(itemPrice).multiply(new BigDecimal(itemAmount)));
											//totalMoney=totalMoney.add(total);
											amount=amount+Long.valueOf(itemAmount);
											m.put("itemPrice", total.divide(new BigDecimal(amount),4,BigDecimal.ROUND_HALF_UP));
											m.put("itemAmount", amount);
											m.put("totalMoney", totalMoney);
											break;
										}
									}
								}else{
									map.put("itemName", adminSku.getProductName());
									map.put("itemPrice", itemPrice);
									map.put("itemAmount", itemAmount);
									map.put("itemUnit", itemUnit);
									totalMoney=totalMoney.add(new BigDecimal(itemPrice));
									map.put("totalMoney", totalMoney);
									skulist.put(adminSku.getProductName(),adminSku.getProductName());
									invoiceList.add(map);
								}

							}else{
								map.put("remark", "SKU不存在");
								continue;
							}
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return invoiceList;
		}
		@RequestMapping("exportInvoiceDetail")
		public void exportInvoiceDetail(Long id,HttpServletRequest request,HttpServletResponse response){
			List<AdminInvoiceDetail> list = adminInvoiceDetailService.findByInvoiceId(id);


			byte[] bytes = fileService.downloadFromOss("template/export_invoice_detail.xlsx"); // ByteToInputStream.input2byte(inputStream);
			List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
			Map<String, Object> dataMap = new HashMap<String, Object>();

			dataMap.put("resultSet", list);
			dataMaps.add(dataMap);
			DocumentHandler.DownloadExcel(bytes, "发票明细.xlsx", dataMap, request, response);
		}
		@RequestMapping("delInvoice")
		@ResponseBody
		public Message delInvoice(Long id,HttpServletRequest request,HttpServletResponse response) {
			adminInvoiceService.deleteSoft(id);
			return SUCCESS_MESSAGE;

		}





}
